import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/api/user'
import { login as loginApi, getProfile } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem('token') || '')
  const user = ref<User | null>(null)
  const isLoggedIn = ref<boolean>(!!token.value)

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const { token: newToken, user: userInfo } = await loginApi(username, password)
      token.value = newToken
      user.value = userInfo
      isLoggedIn.value = true
      localStorage.setItem('token', newToken)
      return true
    } catch (error) {
      return false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const { user: userInfo } = await getProfile()
      user.value = userInfo
      return true
    } catch (error) {
      return false
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    isLoggedIn.value = false
    localStorage.removeItem('token')
  }

  // 检查是否是管理员
  const isAdmin = () => {
    return user.value?.role === 'admin'
  }

  return {
    token,
    user,
    isLoggedIn,
    login,
    fetchUserInfo,
    logout,
    isAdmin
  }
}) 